package com.gogowan.agroenterprise.supply;

import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.IntegrateQuestInfo;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.SupplyDemandDescInfo;
import com.gogowan.agroenterprise.model.SupplyDemandInfo;
import com.gogowan.agroenterprise.model.SupplyDemandResultInfo;
import com.gogowan.agroenterprise.supply.utils.MyListView;
import com.gogowan.agroenterprise.supply.utils.SupplyAndDemandUtils;
import com.gogowan.agroenterprise.supply.utils.MyListView.OnRefreshListener;
import com.gogowan.agroenterprise.utils.Utils;

/**
 * 我的供应列表
 * @author Maniac
 * 2012.12.12
 */
public class MySupplyListActivity extends BaseActivity{
	
	private MyListView mySupplyList;
	private TextView textView;
	private List<SupplyDemandInfo> supplyInfos;
	
	private View bottom;
	private TextView bottomtv;
	private ProgressBar progressBar;
	private LinearLayout bottomLinear;
	
	private SharedPreferences preferences;
	private long enterpriseId;
	private ProgressDialog progressDialog;
	private int clickedPosition;
	private BaseAdapter adapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.supply_my_supply_list);
		
		mySupplyList = (MyListView)findViewById(R.id.supply_my_supply_list);
		bottom = LayoutInflater.from(this).inflate(R.layout.itembottom,null);
		bottomtv = (TextView)bottom.findViewById(R.id.item_bottom_progress_tv);
		progressBar = (ProgressBar)bottom.findViewById(R.id.item_bottom_progressBar);
		bottomLinear = (LinearLayout)bottom.findViewById(R.id.item_bottom_ll);
		//将bottom添加到ListView中的底部
		
		textView = (TextView)findViewById(R.id.supply_my_supply_text);
		
		
		preferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		enterpriseId = preferences.getLong("enterpriseid", 0);
		
		Intent intent = getIntent();
		String string = intent.getStringExtra("myReleases");
		
		if (string == null || string.equals("")) {
			return;
		} else {
			SupplyDemandResultInfo supplyDemandResultInfo = (SupplyDemandResultInfo)Utils.fromJSON(string, SupplyDemandResultInfo.class);
			supplyInfos = supplyDemandResultInfo.getSupplyDemandList();
			
			adapter = new BaseAdapter() {
				
				@Override
				public View getView(int position, View convertView, ViewGroup parent) {
					LayoutInflater inflater=(LayoutInflater)MySupplyListActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
					View layout=inflater.inflate(R.layout.supply_list_item,null);
					TextView textView = (TextView)layout.findViewById(R.id.supply_list_item_text);
					textView.setText(supplyInfos.get(position).getTitle());
					return layout;
				}
				
				@Override
				public long getItemId(int position) {
					return position;
				}
				
				@Override
				public Object getItem(int position) {
					return supplyInfos.get(position);
				}
				
				@Override
				public int getCount() {
					return supplyInfos.size();
				}
			};
			
			if (supplyInfos == null || supplyInfos.size() == 0) {
				return;
			} else {
				textView.setVisibility(View.GONE);
				mySupplyList.setVisibility(View.VISIBLE);
				mySupplyList.setAdapter(adapter);
				
			/*	if (mySupplyList.getLastVisiblePosition() < supplyInfos.size()) {
				} else {
					mySupplyList.addFooterView(bottom);
				}*/
				SupplyAndDemandUtils.addFooterView(adapter, MySupplyListActivity.this, mySupplyList, bottom);
			}
			
			mySupplyList.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					IntegrateQuestInfo integrateQuestInfo = new IntegrateQuestInfo();
					integrateQuestInfo.setSdID(supplyInfos.get(position-1).getSdID());
					integrateQuestInfo.setEnterpriseID(enterpriseId);
					
					progressDialog = ProgressDialog.show(MySupplyListActivity.this,
							getString(R.string.alert_title),
							getString(R.string.alert_message), true, false);
					
					SupplyDetailAsyn supplyDetailAsyn  = new SupplyDetailAsyn(position-1);
					supplyDetailAsyn.execute(integrateQuestInfo);
				}
			});
			
			mySupplyList.setonRefreshListener(new OnRefreshListener() {
				
				@Override
				public void onRefresh() {
					IntegrateQuestInfo integrateQuestInfo = new IntegrateQuestInfo();
					integrateQuestInfo.setEnterpriseID(enterpriseId);
					integrateQuestInfo.setSdID(0);
					/*progressDialog = ProgressDialog.show(MySupplyListActivity.this,
							getString(R.string.alert_title),
							getString(R.string.alert_message), true, false);*/
					
					MYReleasesSupplyAsyn releasesSupplyAsyn = new MYReleasesSupplyAsyn(true);
					releasesSupplyAsyn.execute(integrateQuestInfo);
				}
			});
			
			/*mySupplyList.setOnScrollListener(new OnScrollListener() {
				
				private int lastindex;
				private int totalcount;

				@Override
				public void onScrollStateChanged(AbsListView view, int scrollState) {
					//判断是不是最后一个
					if (scrollState == SCROLL_STATE_IDLE ) {
						if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
							
							//增加记录
							if (supplyInfos == null || supplyInfos.size() == 0) {
								loadRemainListItem(0);
							} else {
								loadRemainListItem(supplyInfos.get(supplyInfos.size() -1).getSdID());
							}
						}
					}
					adapter.notifyDataSetChanged();
				}
				
				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					
					lastindex = firstVisibleItem + visibleItemCount;
		            totalcount = totalItemCount;
				}
			});*/
		}
		
		bottomLinear.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				loadRemainListItem(supplyInfos.get(supplyInfos.size() -1).getSdID());
			}
		});
	}
	
	private void loadRemainListItem(long sdId) {
		bottomtv.setText("正在加载更多.....");
		progressBar.setVisibility(View.VISIBLE);
		
		IntegrateQuestInfo integrateQuestInfo = new IntegrateQuestInfo();
		integrateQuestInfo.setEnterpriseID(enterpriseId);
		integrateQuestInfo.setSdID(sdId);
		/*progressDialog = ProgressDialog.show(MySupplyListActivity.this,
				getString(R.string.alert_title),
				getString(R.string.alert_message), true, false);*/
		
		MYReleasesSupplyAsyn releasesSupplyAsyn = new MYReleasesSupplyAsyn(false);
		releasesSupplyAsyn.execute(integrateQuestInfo);
	}
	/**
	 * 当详细页面处理删除事件时，返回给本Activity删除列表中的数据 并刷新
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 100) {
			if (resultCode == 100) {
				String contents = data.getStringExtra("title");
				if (contents == null || contents.equals("")) {
					
				} else {
					supplyInfos.get(clickedPosition).setTitle(contents);
					adapter.notifyDataSetChanged();
				}
			} else if (resultCode == 200) {
				supplyInfos.remove(clickedPosition);
				adapter.notifyDataSetChanged();
				if (supplyInfos == null || supplyInfos.size() == 0) {
					textView.setVisibility(View.VISIBLE);
					mySupplyList.setVisibility(View.GONE);
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}



	/**
	 * 点击列表项  获取该数据的详细信息
	 * @author Administrator
	 * 2012.12.12
	 */
	private class SupplyDetailAsyn extends MyAsyncTask{

		private int position;
		
		public SupplyDetailAsyn(int position){
			this.position = position;
		}
		
		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(MySupplyListActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(MySupplyListActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					SupplyDemandDescInfo supplyDemandDescInfo = (SupplyDemandDescInfo)Utils.fromJSON(string, SupplyDemandDescInfo.class);
					
					int result = supplyDemandDescInfo.getResult();
					
					if (result == 6210) {
						clickedPosition = position;
						Intent intent = new Intent(MySupplyListActivity.this,CheckMySupplyActivity.class);
						intent.putExtra("myDetail", string);
						startActivityForResult(intent, 100);
						Utils.randomAnim(MySupplyListActivity.this);
						
					} else {
						Toast.makeText(MySupplyListActivity.this, supplyDemandDescInfo.getResultinfo(), Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			IntegrateQuestInfo request = (IntegrateQuestInfo)params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(6200, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
		
	}
	
	public void showFinishDialog(String s,String string){
    	new AlertDialog.Builder(MySupplyListActivity.this).setTitle(s)
		.setMessage(string).setPositiveButton("确定", new DialogInterface.OnClickListener() {
	
			@Override
			public void onClick(DialogInterface dialog, int which) {
				MySupplyListActivity.this.finish();
			}
		}).create().show();
    }
	/**
	 * 查看我的供应列表
	 * @author Maniac
	 * 2012.12.12
	 */
	private class MYReleasesSupplyAsyn extends MyAsyncTask{

		private boolean isRefresh;
		
		public MYReleasesSupplyAsyn(boolean isRefresh) {
			this.isRefresh = isRefresh;
		}
		
		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				if (isRefresh) {
					mySupplyList.onRefreshComplete();
				}
				Toast.makeText(MySupplyListActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					if (isRefresh) {
						mySupplyList.onRefreshComplete();
					}
					Toast.makeText(MySupplyListActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					
					SupplyDemandResultInfo supplyDemandResultInfo = (SupplyDemandResultInfo)Utils.fromJSON(string, SupplyDemandResultInfo.class);
					int result = supplyDemandResultInfo.getResult();
					if (result == 6510) {
						progressBar.setVisibility(View.GONE);
						List<SupplyDemandInfo> cInfo = supplyDemandResultInfo.getSupplyDemandList();
						if (isRefresh) {
							if (cInfo ==null || cInfo.size() == 0) {
								Toast.makeText(MySupplyListActivity.this, "刷新失败", Toast.LENGTH_LONG).show();
							} else {
								Toast.makeText(MySupplyListActivity.this, "刷新成功", Toast.LENGTH_LONG).show();
								supplyInfos = cInfo;
								if (supplyInfos == null || supplyInfos.size() == 0) {
									Toast.makeText(MySupplyListActivity.this, "刷新失败", Toast.LENGTH_LONG).show();
								} else {
									adapter.notifyDataSetChanged();
								}
							}
							mySupplyList.onRefreshComplete();
						} else {
							if (cInfo ==null || cInfo.size() == 0) {
								Toast.makeText(MySupplyListActivity.this, "获取更多信息失败", Toast.LENGTH_LONG).show();
							} else {
								for (int i = 0; i < cInfo.size(); i++) {
									supplyInfos.add(cInfo.get(i));
								}
								
								if (supplyInfos == null || supplyInfos.size() == 0) {
									Toast.makeText(MySupplyListActivity.this, "获取更多信息失败", Toast.LENGTH_LONG).show();
								} else {
									adapter.notifyDataSetChanged();
								}
								bottomtv.setText("更多");
								progressBar.setVisibility(View.GONE);
							}
						}
					} else {
						if (isRefresh) {
							mySupplyList.onRefreshComplete();
							Toast.makeText(MySupplyListActivity.this, "刷新失败", Toast.LENGTH_LONG).show();
						} else {
							bottomtv.setText("更多");
							progressBar.setVisibility(View.GONE);
							Toast.makeText(MySupplyListActivity.this, "列表内容已全部显示", Toast.LENGTH_LONG).show();
						}
					}
				}
			}
			
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			
			IntegrateQuestInfo request = (IntegrateQuestInfo)params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(6500, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}
/*	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			AlertDialog alert = new AlertDialog.Builder(MySupplyListActivity.this)
			.setTitle(getString(R.string.tip_back))
			.setMessage(getString(R.string.tip_back_description)).setCancelable(false)
					.setNegativeButton("否", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// do nothing
						}
					})
					.setPositiveButton("是", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// 结束应用程序
							MySupplyListActivity.this.finish();
							Utils.randomAnim(MySupplyListActivity.this);
						}
					}).create();
			alert.show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}*/
}
